package xyz.zcq.zcqrpc.serializer;

import com.fasterxml.jackson.databind.ObjectMapper;
import xyz.zcq.zcqrpc.model.RpcRequest;
import xyz.zcq.zcqrpc.model.RpcResponse;

import java.io.IOException;

/**
 * Json序列化器
 */
public class JsonSerializer implements Serializer {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public <T> byte[] serialize(T object) throws IOException {
        return OBJECT_MAPPER.writeValueAsBytes(object);
    }

    @Override
    public <T> T deserialization(byte[] bytes, Class<T> clazz) throws IOException {
        T t = OBJECT_MAPPER.readValue(bytes, clazz);

        if (t instanceof RpcRequest) {
            RpcRequest rpcRequest = (RpcRequest) t;
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Object[] parameters = rpcRequest.getParameters();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];
                if (!parameterType.isAssignableFrom(parameters[i].getClass())) {
                    parameters[i] = OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsBytes(parameters[i]), parameterType);
                }
            }
            t = clazz.cast(rpcRequest);
        } else if (t instanceof RpcResponse) {
            RpcResponse rpcResponse = (RpcResponse) t;
            rpcResponse.setData(
                    OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsBytes(rpcResponse.getData()), rpcResponse.getDataType())
            );
            t = clazz.cast(rpcResponse);
        }
        return t;
    }

}
